from entity import entity
from component import componentMeta as meta, component
from datetime import datetime
from constants import mud, messagetype
from os import path
import logging
logger = logging.getLogger(__name__)

class player(component):
    __metaclass__ = meta
    _name = 'player'
    """
    This is the component class for the player, that holds all the required information.
    """
    requires=['living']
    password = ""
    creation = datetime.now()
    lastlog = datetime.now()
def message(obj, message, type=messagetype.info):
    """
    writes a message to the player.
    """
    if obj == None:
        raise ValueError("Obj must be a valid object.")
    if obj.client == None:
        raise ValueError("The object has no socket associated with it.")
    obj.client.writeline(message)

def save(obj):
    if obj == None:
        raise ValueError("Obj must be an entity object when calling Save.")

    com = obj.getComponent("player")
    if com == None:
        raise ValueError("The specified object does not have the player component.")

    fpath = path.join(mud.playerdir, obj.name.lower())
    obj.serialize(fpath)

def create(client):
    """
    Creates a player from a client and saves.
    """
    obj = entity()
    obj.name = client.name
    obj.attachComponent("player")
    com = obj.getComponent("player")
    com.password = client.password
    com.creation = datetime.now()
    com.lastlog = com.creation
    save(obj)

def login(client, world):
    """
    Logs the player in to the mud.
    """
    pfile = path.join(mud.playerdir, client.name.lower())
    if not path.exists(pfile):
        raise ValueError("The specified player does not exist.")

    obj = entity.deserialize(pfile)
    pcom = obj.getComponent("player")
    if pcom == None:
        logger.error("player %s logged in, but does not have a player component.")
        client.writeline("There appears to be an error with your player file, please contact an administrator.")
        return

    if not pcom.password == client.password:
        raise ValueError("Invalid user or pass, please try again.")

    obj.client = client
    obj.calculateDependencies() #we make sure there were no changes to components since we logged in last.
    client.player = obj
    pcom.lastlog = datetime.now()
    world.players.append(obj)
    client.writeline("Welcome back!")
    